using System;
using System.Collections.Generic;
using System.IO;
using Blader.Config;
using Blader.Entity;
using Blader.UI.TextBox;

namespace Blader.Cache
{
    public class CacheService
    {
        private static readonly CacheService instance = new CacheService();

        AutoCompleteEntryCollection projectSqlFilesCache = new AutoCompleteEntryCollection();
        Dictionary<string, AutoCompleteEntryCollection> solutionSqlFilesCache = new Dictionary<string, AutoCompleteEntryCollection>();

        public static CacheService GetCacheService()
        {
            return instance;
        }

        public bool Flush()
        {
            projectSqlFilesCache.Clear();
            solutionSqlFilesCache.Clear();
            return true;
        }

        public AutoCompleteEntryCollection LoadSolutionSqlFiles(string solutionPath)
        {
            if (!solutionSqlFilesCache.ContainsKey(solutionPath))
            {
                FileInfo fileInfo = new FileInfo(solutionPath);

                DirectoryInfo[] dataBaseDirectoty = fileInfo.Directory.GetDirectories("Database");

                AutoCompleteEntryCollection autoCompleteEntryCollection = new AutoCompleteEntryCollection();

                foreach (DirectoryInfo directoryInfo in dataBaseDirectoty)
                {
                    FileInfo[] sqlFiles = directoryInfo.GetFiles("*.sql", SearchOption.AllDirectories);

                    foreach (FileInfo sqlFile in sqlFiles)
                    {
                        autoCompleteEntryCollection.Add(new AutoCompleteEntry(sqlFile.Name, sqlFile.FullName, string.Empty));
                    }
                }
                autoCompleteEntryCollection.Sort((a, b) => string.Compare(a.DisplayName, b.DisplayName));
                solutionSqlFilesCache.Add(solutionPath, autoCompleteEntryCollection);
            }

            return solutionSqlFilesCache[solutionPath];
        }

        public AutoCompleteEntryCollection LoadProjectSqlFiles()
        {
            if (projectSqlFilesCache.Count != 0) return projectSqlFilesCache;

            ConfigReader configReader = ConfigReader.GetInstance();

            List<ProjectItem> projectItems = configReader.LoadProjects();

            foreach (ProjectItem projectItem in projectItems)
            {
                if (!projectItem.Active) continue;

                string[] files = Directory.GetFiles(projectItem.Path, "*.sql", SearchOption.AllDirectories);

                foreach (string file in files)
                {
                    projectSqlFilesCache.Add(new AutoCompleteEntry(new FileInfo(file).Name, file, projectItem.Label));
                }
            }

            projectSqlFilesCache.Sort((a, b) => string.Compare(a.DisplayName, b.DisplayName));

            return projectSqlFilesCache;
        }

    }
}